package logic

import (
	"context"
	"errors"
	"fmt"
	"pet/models"

	"pet/petrpc/internal/svc"
	"pet/petrpc/petrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type PetAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewPetAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PetAddLogic {
	return &PetAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *PetAddLogic) PetAdd(in *petrpc.PetAddRequest) (*petrpc.PetAddResponse, error) {
	// todo: add your logic here and delete this line

	class := models.Class{
		Name: in.ClassName,
	}

	err := models.DB.Debug().Where("name = ?", in.ClassName).FirstOrCreate(&class).Error
	if err != nil {
		errors.New("类型添加失败")
	}

	pes := models.Pes{
		Name: in.PesName,
	}

	models.DB.Debug().Where("name = ?", in.PesName).FirstOrCreate(&pes)

	pet := models.Pet{
		Name:    in.Name,
		Sex:     in.Sex,
		Info:    in.Info,
		Image:   in.Image,
		ClassId: int64(class.ID),
	}

	err = models.DB.Debug().Where("name = ?", pet.Name).Find(&pet).Error
	if err != nil {
		fmt.Errorf("宠物名称重复")
	}

	err = models.DB.Debug().Create(&pet).Error
	if err != nil {
		errors.New("添加失败")
	}

	return &petrpc.PetAddResponse{
		PetId: int64(pet.ID),
	}, nil
}
